import { app, BrowserWindow } from "electron";
import * as path from "path";
import { format as formatUrl } from "url";
import {registerMangaCover} from "./function/protocolFunc";
const isDevelopment = process.env.NODE_ENV !== "production";

let mainWin: BrowserWindow = null;

function createMainWindow() {
    const window: BrowserWindow = new BrowserWindow({
        width: 1200,
        height: 800,
        webPreferences: {
            nodeIntegration: true,
        },
        autoHideMenuBar: true,
    });

    if (isDevelopment) {
        window.webContents.openDevTools();
    }

    if (isDevelopment) {
        window.loadURL(`http://localhost:${process.env.ELECTRON_WEBPACK_WDS_PORT}`);
    } else {
        window.loadURL(formatUrl({
            pathname: path.join(__dirname, "index.html"),
            protocol: "file",
            slashes: true,
        }));
    }

    window.on("closed", () => {
        mainWin = null;
    });

    window.webContents.on("devtools-opened", () => {
        window.focus();
        setImmediate(() => {
            window.focus();
        });
    });

    return window;
}

app.on("ready", () => {
    registerMangaCover();
    mainWin = createMainWindow();
});

app.on("activate", () => {
    // on macOS it is common to re-create a window even after all windows have been closed
    if (mainWin === null) {
        mainWin = createMainWindow();
    }
});

app.on("window-all-closed", () => {
    app.quit();
});
